package com.unionftech.common.utils;

import android.content.Context;
import android.os.Parcelable;

import com.tencent.mmkv.MMKV;

import java.util.Set;

public class SpUtils {
    private static String cryptKey = "p3MK5J4ecNjQBZp4KNCSYKdTSjGXtTUGETXGavxjCWGsRsj4XSQGyQBrGMZ6Zx4S";
    private static SpUtils instance;
    private MMKV mmkv;

    private SpUtils() {
    }

    public static SpUtils getInstance() {
        if (instance == null) {
            synchronized (SpUtils.class) {
                if (instance == null) {
                    instance = new SpUtils();
                }
            }
        }
        return instance;
    }

    public void init(Context context) {
        MMKV.initialize(context);
        if (mmkv == null) {
            mmkv = MMKV.defaultMMKV(MMKV.SINGLE_PROCESS_MODE, cryptKey);
        }
    }

    /**
     * 保存数据
     *
     * @param key
     * @param value
     */
    public void put(String key, Object value) {
        if (value instanceof String) {
            mmkv.encode(key, (String) value);
        } else if (value instanceof Integer) {
            mmkv.encode(key, (Integer) value);
        } else if (value instanceof Boolean) {
            mmkv.encode(key, (Boolean) value);
        } else if (value instanceof Float) {
            mmkv.encode(key, (Float) value);
        } else if (value instanceof Long) {
            mmkv.encode(key, (Long) value);
        } else if (value instanceof Double) {
            mmkv.encode(key, (Double) value);
        } else if (value instanceof byte[]) {
            mmkv.encode(key, (byte[]) value);
        } else {
            mmkv.encode(key, value.toString());
        }
    }

    public void put(String key, Set<String> value) {
        mmkv.encode(key, value);
    }

    public void put(String key, Parcelable obj) {
        mmkv.encode(key, obj);
    }

    public String getString(String key) {
        return mmkv.decodeString(key, "");
    }

    public int getInt(String key) {
        return mmkv.decodeInt(key, 0);
    }

    public boolean getBoolean(String key) {
        return mmkv.decodeBool(key, false);
    }

    public boolean getBoolean(String key, boolean defaultValue) {
        return mmkv.decodeBool(key, defaultValue);
    }

    public float getFloat(String key) {
        return mmkv.decodeFloat(key, 0f);
    }

    public long getLong(String key) {
        return mmkv.decodeLong(key, 0L);
    }

    public double getDouble(String key) {
        return mmkv.decodeDouble(key, 0.0);
    }

    public byte[] getBytes(String key) {
        return mmkv.decodeBytes(key);
    }

    public Set<String> getStringSet(String key) {
        return mmkv.decodeStringSet(key);
    }

    public <T extends Parcelable> Parcelable getParcelable(String key, Class<T> clazz) {
        return mmkv.decodeParcelable(key, clazz);
    }

    public void remove(String key) {
        mmkv.removeValueForKey(key);
    }

    public void clearAll() {
        mmkv.clearAll();
    }
}
